﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Windows;

namespace SpectrumAnalyser.ModelObjects
{
    [Serializable]
    public class Peak:INotifyPropertyChanged
    {
        public SpectrumPoint Point1 { get; set; }
        public SpectrumPoint Point2 { get; set; }
        public SpectrumPoint Point3 { get; set; }

        /// <summary>
        /// Original spectrum points data.
        /// </summary>
        public List<SpectrumPoint> Points { get; set; }

        /// <summary>
        /// Use for proection original point data to chart plot.
        /// </summary>
        public List<SpectrumPoint> ViewPoints { get; set; }

        public IList<ChemicalElement> MatchedChemicalElements { get; set; }
        private bool _isVisible;

        public bool IsVisible
        {
            get { return _isVisible; }
            set
            {
                _isVisible = value;
                OnPropertyChanged("IsVisible");
            }
        }

        public double Height
        {
            get
            {
                return (Point2 == null || Point1 == null || Point3 == null)
                           ? 0
                           : Point2.Y - Math.Abs(Point1.Y + Point3.Y)/2;
            }
        }

        public double Width
        {
            get { return Math.Abs(Point1.X - Point3.X); }
        }

        public string Info
        {
            get
            {
                if (MatchedChemicalElements != null && MatchedChemicalElements.Any())
                {
                    var selectedElement = MatchedChemicalElements.FirstOrDefault(x => x.IsVisible);
                    return string.Format("{0}; {1}; {2}.", Point2.Y,
                                         selectedElement == null ? string.Empty : selectedElement.Name,
                                         selectedElement == null
                                             ? string.Empty
                                             : selectedElement.IonizationStage.ToString(CultureInfo.InvariantCulture));
                }else
                {
                    return Point2.Y.ToString(CultureInfo.InvariantCulture);
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}